<?php
namespace app\models;

use yii\db\ActiveRecord;

/**
 * 用户设置
 *
 * Class UserConfig
 * @package app\models
 *
 * @property integer $id
 * @property integer $uid
 * @property string $k
 * @property string $v
 */
class UserConfig extends ActiveRecord
{
    const VERIFY_EMAIL = 'verify_email';
    const VERIFY_EMAIL_VCODE = 'verify_email_vcode';
    
    const BIND_ALIPAY = 'bind_alipay';
    const BIND_BANK   = 'bind_bank';

    /**
     * 保存用户设置
     * @param integer $uid 用户编号
     * @param string $k 名称
     * @param string $v 内容
     * @return boolean
     */
    public static function setConfig($uid, $k, $v)
    {
        $model = self::find()->where([
            'uid'=>$uid,
            'k'=>$k
        ])->one();
        if (empty($model)) {
            $model = new UserConfig();
            $model->uid = $uid;
            $model->k = $k;
        }
        $model->v = $v;
        return $model->save();
    }

    /**
     * 获取用户设置
     * @param integer $uid 用户编号
     * @param integer $k 设置名称
     * @param mixed $v='' 默认值
     * @return string
     */
    public static function getConfig($uid, $k, $v = '')
    {
        /* @var $model UserConfig */
        $model = self::find()->where([
            'uid'=>$uid,
            'k'=>$k
        ])->one();
        if (!empty($model)) {
            return $model->v;
        }
        return $v;
    }

    /**
     * 返回用户所有配置
     * @param $uid
     * @return array
     */
    public static function getAllConfig($uid)
    {
        $model_list = self::find()->where('uid = ' . $uid)->all();
        $config = [];
        foreach ($model_list as $model) {
            /* @var $model UserConfig */
            $config[$model->k] = $model->v;
        }
        return $config;
    }
}
